let logger = require("pomelo-logger").getLogger(__filename);

module.exports = function (app) {
    return new Handler(app);
};

let Handler = function (app) {
    this.app = app;
};

Handler.prototype.readMail = function (msg, session, callback) {
    let id = msg["id"];
    let player = session["player"];
    if (!session.player) {
        logger.error("readMail empty player");
        callback(null, {resultCode: 404, message: "请先登录"});
        return;
    }
    let mail = player.readMail(id);
    let playerService = this.app.get("playerService");
    playerService.save(player);
    if (!!mail) {
        if (!!mail.getAward()) {
            callback(null, {
                resultCode: 0,
                message: "ok",
                award: mail.getAward()
            });
        } else {
            callback(null, {
                resultCode : 0,
                message: "ok"
            })
        }

        if(mail.hasAward()) {
            player.pushDeleteMails([mail.getId()]);
        }else if (player.containMail(mail.getId())) {
            player.pushUpdateMails([mail.getId()]);
        }
    } else {
        callback(null, {
            resultCode: 404,
            message: "没有找到此邮件"
        });
    }
};

Handler.prototype.deleteMail = function (msg, session, callback) {
    logger.info("deleteMail.msg=" + JSON.stringify(msg) + "frontendId=" + session["frontendId"] + " id=" + session["id"]);
    if (!msg.hasOwnProperty("id")) {
        logger.error("deleteMail empty id");
        callback(null, {
            resultCode: 404,
            message: "参数id为空"
        });
        return;
    }
    let id = msg["id"];
    let player = session["player"];
    if (!session.player) {
        logger.error("readMail empty player");
        callback(null, {
            resultCode: 404,
            message: "请先登录"
        });
        return;
    }
    let mail = player.deleteMail(id);
    if (!!mail) {
        callback(null, {
            resultCode: 0,
            message: "ok"
        });
        player.pushDeleteMails([id]);
    } else {
        callback(null, {
            resultCode: 404,
            message: "删除邮件失败"
        });
    }
};

Handler.prototype.readAllMails = function (msg, session, callback) {
    logger.info("readAllMails.msg=" + JSON.stringify(msg) + "frontendId=" + session["frontendId"] + " id=" + session["id"]);
    let player = session["player"];
    if (!session.player) {
        logger.error("readAllMails empty player");
        callback(null, {
            resultCode: 404,
            message: "请先登录"
        });
        return;
    }
    let mails = player.readAllMails();
    let awards = [];
    for (var idx in mails) {
        let mail = mails[idx];
        awards.push(mail.getAward());
    }
    callback(null, {
        resultCode: 0,
        message: "ok",
        awards: awards
    });
    player.pushSetAllMails();
};

